package com.summit.exam.servlet;

import com.summit.exam.dbdao.StudentDao;
import com.summit.exam.dbdao.UserInfoDao;
import com.summit.exam.entity.StudentBean;
import com.summit.exam.entity.UserInfoBean;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

public class ForgetPasswordServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html; charset=utf-8");

        String uname = req.getParameter("pawd_ipt_name");
        String upawd = req.getParameter("pawd_ipt_pass2");

        StudentDao studentService = new StudentDao();
        UserInfoDao userInfoDao = new UserInfoDao();
        PrintWriter pw = resp.getWriter();

        List<UserInfoBean> userInfoBean = userInfoDao.queryStudent(uname);
        System.out.println(userInfoBean.toString());

        if (userInfoBean != null && userInfoBean.size() != 0
                && userInfoBean.get(0).getUserLoginName() != null){
            //修改密码
            Boolean result = studentService.updatePassword(uname,upawd);
            Boolean ok = userInfoDao.updatePassword(uname,upawd);
            if(!result && !ok){
                pw.println("<script language='javascript'>alert('修改失败，请联系管理员！')</script>");
                pw.println("<script>window.history.go(-1)</script>");
            }else {
                pw.println("<script language='javascript'>alert('修改成功')</script>");
                pw.println("<script>window.history.go(-1)</script>");

                resp.sendRedirect(req.getContextPath() + "/ExamSystem/techweb/register.jsp");
            }

        }else {
            pw.println("<script language='javascript'>alert('修改失败，用户不存在，请重试！')</script>");
            pw.println("<script>window.history.go(-1)</script>");
        }


    }
}
